"""
Web应用主模块

基于Flask的Web管理界面
"""

import os
import json
from datetime import datetime
from typing import Dict, Any, Optional
from flask import Flask, render_template, jsonify, request, send_from_directory
from flask_cors import CORS

from ..core import unified_logger
from ..monitoring import unified_monitor
from .api import APIRouter
from .websocket import WebSocketManager


class WebApp:
    """Web应用类"""
    
    def __init__(self, config: Optional[Dict[str, Any]] = None):
        """
        初始化Web应用
        
        Args:
            config: 应用配置
        """
        self.config = config or self._get_default_config()
        self.logger = unified_logger.get_logger('web_app')
        
        # Flask应用
        self.app = None
        
        # 监控组件
        self.dashboard = None
        self.system_monitor = None
        self.strategy_monitor = None
        self.alert_manager = None
        self.notification_manager = None
        
        # API路由器
        self.api_router = None
        
        # WebSocket管理器
        self.websocket_manager = None
        
        self.logger.info("Web应用初始化完成")
    
    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            'host': '0.0.0.0',
            'port': 8080,
            'debug': False,
            'secret_key': 'xcquant-web-secret-key',
            'template_folder': 'templates',
            'static_folder': 'static',
            'enable_cors': True,
            'enable_websocket': True,
            'websocket_port': 8765
        }
    
    def setup_monitoring(self, monitor=None):
        """设置监控组件"""
        self.monitor = monitor or unified_monitor
        
        self.logger.info("监控组件已设置")
    
    def create_app(self) -> Flask:
        """创建Flask应用"""
        # 创建Flask实例
        template_folder = os.path.join(os.path.dirname(__file__), self.config['template_folder'])
        static_folder = os.path.join(os.path.dirname(__file__), self.config['static_folder'])
        
        self.app = Flask(__name__,
                        template_folder=template_folder,
                        static_folder=static_folder)
        
        # 配置应用
        self.app.config['SECRET_KEY'] = self.config['secret_key']
        self.app.config['DEBUG'] = self.config['debug']
        
        # 启用CORS
        if self.config['enable_cors']:
            CORS(self.app)
        
        # 设置API路由器
        self.api_router = APIRouter(self.dashboard)
        self.api_router.register_routes(self.app)
        
        # 设置WebSocket管理器
        if self.config['enable_websocket']:
            self.websocket_manager = WebSocketManager(
                self.dashboard,
                port=self.config['websocket_port']
            )
        
        # 注册路由
        self._register_routes()
        
        # 注册错误处理器
        self._register_error_handlers()
        
        self.logger.info("Flask应用创建完成")
        return self.app
    
    def _register_routes(self):
        """注册路由"""
        
        @self.app.route('/')
        def index():
            """首页"""
            return render_template('index.html')
        
        @self.app.route('/dashboard')
        def dashboard():
            """监控面板"""
            return render_template('dashboard.html')
        
        @self.app.route('/strategies')
        def strategies():
            """策略管理"""
            return render_template('strategies.html')
        
        @self.app.route('/alerts')
        def alerts():
            """告警管理"""
            return render_template('alerts.html')
        
        @self.app.route('/settings')
        def settings():
            """系统设置"""
            return render_template('settings.html')
        
        @self.app.route('/reports')
        def reports():
            """报告查看"""
            return render_template('reports.html')
        
        @self.app.route('/data-manager')
        def data_manager():
            """数据管理"""
            return render_template('data_manager.html')
        
        @self.app.route('/strategy-manager')
        def strategy_manager():
            """策略管理"""
            return render_template('strategy_manager.html')
        
        @self.app.route('/live-trading')
        def live_trading():
            """实盘交易"""
            return render_template('live_trading.html')
        
        # 静态文件路由
        @self.app.route('/static/<path:filename>')
        def static_files(filename):
            """静态文件服务"""
            return send_from_directory(self.app.static_folder, filename)
        
        # 健康检查
        @self.app.route('/health')
        def health_check():
            """健康检查"""
            if self.dashboard:
                health = self.dashboard.get_system_health()
                return jsonify(health)
            else:
                return jsonify({
                    'overall_status': 'warning',
                    'message': '监控面板未初始化'
                })
        
        # 系统信息
        @self.app.route('/info')
        def system_info():
            """系统信息"""
            return jsonify({
                'name': 'XCQuant Web管理界面',
                'version': '1.0.0',
                'timestamp': datetime.now().isoformat(),
                'config': {
                    'host': self.config['host'],
                    'port': self.config['port'],
                    'debug': self.config['debug'],
                    'enable_websocket': self.config['enable_websocket'],
                    'websocket_port': self.config['websocket_port']
                }
            })
    
    def _register_error_handlers(self):
        """注册错误处理器"""
        
        @self.app.errorhandler(404)
        def not_found(error):
            """404错误处理"""
            if request.path.startswith('/api/'):
                return jsonify({
                    'success': False,
                    'error': 'API endpoint not found'
                }), 404
            return render_template('error.html', 
                                 error_code=404, 
                                 error_message='页面未找到'), 404
        
        @self.app.errorhandler(500)
        def internal_error(error):
            """500错误处理"""
            self.logger.error(f"内部服务器错误: {error}")
            if request.path.startswith('/api/'):
                return jsonify({
                    'success': False,
                    'error': 'Internal server error'
                }), 500
            return render_template('error.html',
                                 error_code=500,
                                 error_message='内部服务器错误'), 500
        
        @self.app.errorhandler(Exception)
        def handle_exception(error):
            """通用异常处理"""
            self.logger.error(f"未处理的异常: {error}")
            if request.path.startswith('/api/'):
                return jsonify({
                    'success': False,
                    'error': str(error)
                }), 500
            return render_template('error.html',
                                 error_code=500,
                                 error_message=str(error)), 500
    
    def run(self, host: str = None, port: int = None, debug: bool = None):
        """运行Web应用"""
        if not self.app:
            self.create_app()
        
        # 启动WebSocket服务器
        if self.websocket_manager:
            self.websocket_manager.start()
        
        # 运行Flask应用
        run_config = {
            'host': host or self.config['host'],
            'port': port or self.config['port'],
            'debug': debug if debug is not None else self.config['debug']
        }
        
        self.logger.info(f"启动Web服务器: {run_config['host']}:{run_config['port']}")
        self.app.run(**run_config)
    
    def stop(self):
        """停止Web应用"""
        if self.websocket_manager:
            self.websocket_manager.stop()
        
        self.logger.info("Web应用已停止")


def create_app(config: Optional[Dict[str, Any]] = None) -> Flask:
    """
    创建Flask应用的工厂函数
    
    Args:
        config: 应用配置
        
    Returns:
        Flask应用实例
    """
    web_app = WebApp(config)
    return web_app.create_app()


# 用于开发环境的应用实例
app = None

def get_app() -> Flask:
    """获取应用实例"""
    global app
    if app is None:
        app = create_app()
    return app


if __name__ == '__main__':
    # 开发环境启动
    web_app = WebApp({'debug': True})
    web_app.run()